/**
 * @file dlight_bh1750.cpp
 * @author LinTeX9527 (lintex9527@yeah.net)
 * @brief BH1750 测光，获取光强度 lux 数值
 * @version 0.1
 * @date 2024-11-09
 *
 * @copyright Copyright (c) 2024
 *
 */

/* Includes --------------------------------------------------------------------------------------*/

#include <Arduino.h>
#include <Wire.h>
#include <BH1750.h>
#include "dlight_bh1750.h"

/* Constants -------------------------------------------------------------------------------------*/

#define BH1750_I2C_ADDR       0x23

/* Variables -------------------------------------------------------------------------------------*/

BH1750 lightmeter(BH1750_I2C_ADDR); /* 构造对象 */

double g_lux = 0.0; /* 环境光强度 */

/* Function Implementations ----------------------------------------------------------------------*/

/**
 * @brief BH1750 环境光传感器初始化
 *
 * @return int 0 on success; -1 on error.
 */
int setup_bh1750(void)
{
	int retval = 0;

	Wire.begin();

	if (lightmeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
		Serial.println(F("BH1750 Advanced begin"));
	} else {
		Serial.println(F("Error: BH1750 init"));
		retval = -1;
	}

	return retval;
}

/**
 * @brief BH1750 测光
 * 已经对 BH1750 测光过程的延时进行了处理，如果不能读取测光结果则返回 false，否则返回 true 并返回当前读取的数值。
 * @return true 测光数值有效
 * @return false 测光失败
 */
bool loop_bh1750_scan(void)
{
	double lux = 0.0;

	if (lightmeter.measurementReady()) {
		lux = lightmeter.readLightLevel();
		Serial.println(">lux: " + String(lux));

		g_lux = lux;
		return true;
	}

	return false;
}

/**
 * @brief 在调用 loop_bh1750_scan() 成功之后才需要调用这个函数获取
 *
 * @return float
 */
double bh1750_get_lux(void)
{
	return g_lux;
}
